package com.itheima.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.store.QuestionDao;
import com.itheima.domain.store.Question;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.QuestionService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: mm
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-15 14:05
 **/
public class QuestionServiceImpl implements QuestionService {
    @Override
    public String save(Question question) {
        SqlSession sqlSession = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //id使用UUID的生成策略来获取
            String id = UUID.randomUUID().toString();
            question.setId(id);

            //设置新创建的题目默认的审核状态为未审核（0）
            question.setReviewStatus("0");
            question.setCreateTime(new Date());

            //设置图片名称唯一
            question.setPicture(id);

            //3.调用Dao层操作
            questionDao.save(question);

            //
            //4.提交事务
            TransactionUtil.commit(sqlSession);
            return id;
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delete(Question question) {
        SqlSession sqlSession = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            questionDao.delete(question);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(Question question) {
        SqlSession sqlSession = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            questionDao.update(question);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Question findById(String id) {
        SqlSession sqlSession = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            return questionDao.findById(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Question> findAll() {
        SqlSession sqlSession = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            return questionDao.findAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageInfo findAll(int page, int size) {
        SqlSession sqlSession = null;
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            PageHelper.startPage(page, size);
            List<Question> all = questionDao.findAll();
            PageInfo pageInfo = new PageInfo(all);
            return pageInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public ByteArrayOutputStream getReport() throws IOException {
        SqlSession sqlSession = null;
        List<Question> questionList = new ArrayList<>();
        try {
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
            //3.调用Dao层操作
            questionList = questionDao.findAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //创建工作表
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建sheet
        XSSFSheet sheet = workbook.createSheet("题目数据文件");
        //设置通用配置 居中和边框
        // sheet.setColumnWidth(4, 100);
        XSSFCellStyle cs_field = workbook.createCellStyle();
        cs_field.setVerticalAlignment(VerticalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);

        //制作标题
        XSSFRow row_1 = sheet.createRow(1);
        XSSFCell cell_1_11 = row_1.createCell(1);
        cell_1_11.setCellValue("在线实体导出信息");

        //标题样式
        XSSFCellStyle cs_title = workbook.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);

        cell_1_11.setCellStyle(cs_title);

        //合并单元格
        CellRangeAddress region = new CellRangeAddress(1, 1, 1, 12);
        sheet.addMergedRegion(region);

        //制作表头
        String[] fields = {"题目ID", "所属公司ID", "所属目录ID", "题目简介", "题干描述",
                "题干配图", "题目分析", "题目类型", "题目难度", "是否经典题", "题目状态", "审核状态"};

        XSSFRow row = sheet.createRow(2);
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            XSSFCell cell_2_tmp = row.createCell(i + 1);
            cell_2_tmp.setCellValue(field);

            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            cell_2_tmp.setCellStyle(style);
        }

        //
        for (int i = 0; i < questionList.size(); i++) {
            Question question = questionList.get(i);
            //3行开始
            XSSFRow row_i = sheet.createRow(i + 3);
            //1列
            XSSFCell cell_i_1 = row_i.createCell(1);
            cell_i_1.setCellValue(question.getId());
            //2列
            XSSFCell cell_i_2 = row_i.createCell(2);
            cell_i_2.setCellValue(question.getCompanyId());
            //3列
            XSSFCell cell_i_3 = row_i.createCell(3);
            cell_i_3.setCellValue(question.getCatalogId());
            //4列
            XSSFCell cell_i_4 = row_i.createCell(4);
            cell_i_4.setCellValue(question.getRemark());
            //5列
            XSSFCell cell_i_5 = row_i.createCell(5);
            cell_i_5.setCellValue(question.getSubject());
            //6列
            XSSFCell cell_i_6 = row_i.createCell(6);
            cell_i_6.setCellValue(question.getPicture());
            //7列
            XSSFCell cell_i_7 = row_i.createCell(7);
            cell_i_7.setCellValue(question.getAnalysis());
            //8列
            XSSFCell cell_i_8 = row_i.createCell(8);
            cell_i_8.setCellValue(question.getType());
            //9列
            XSSFCell cell_i_9 = row_i.createCell(9);
            cell_i_9.setCellValue(question.getDifficulty());
            //10列
            XSSFCell cell_i_10 = row_i.createCell(10);
            cell_i_10.setCellValue(question.getIsClassic());
            //11列
            XSSFCell cell_i_11 = row_i.createCell(11);
            cell_i_11.setCellValue(question.getState());
            //12列
            XSSFCell cell_i_12 = row_i.createCell(12);
            cell_i_12.setCellValue(question.getReviewStatus());

        }
        //将数据写入到流中
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // FileOutputStream stream = new FileOutputStream("模板.xlsx");
        workbook.write(os);
        //关闭文件流
        os.close();
        //关闭工作表
        workbook.close();
        return os;
    }
}